package com.cw2.behavioral.chain.ext;

import com.cw2.behavioral.command.Command;

import java.util.ArrayList;
import java.util.List;

public class FilterChain implements Filter{

    // 记录当前执行的步骤
    int cursor = 0;

    // filter链
    List<Filter> filterChain = new ArrayList<>();

    // 最终要执行的方法
    My target;

    public void setTarget(My target) {
        this.target = target;
    }

    public My getTarget() {
        return target;
    }

    void addFilter(Filter filter){
        filterChain.add(filter);
    }

    @Override
    public void doFilter(Request request, Response response, FilterChain chain) {
        // 第一次执行第一个filter,依次往下执行
        if (cursor < filterChain.size()){
            Filter filter = filterChain.get(cursor);
            cursor ++;
            // 执行filter方法
            filter.doFilter(request, response, chain);
        }else {
            // 执行最终的方法
            target.hello();
        }


    }
}
